package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.zzyl.base.ResponseResult;
import com.zzyl.constant.AccraditationRecordConstant;
import com.zzyl.dto.CheckInConfigDto;
import com.zzyl.entity.*;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.BedMapper;
import com.zzyl.mapper.CheckInConfigMapper;
import com.zzyl.mapper.CheckInMapper;
import com.zzyl.mapper.ElderMapper;
import com.zzyl.service.AccraditationRecordService;
import com.zzyl.service.ActFlowCommService;
import com.zzyl.service.CheckInConfigService;
import com.zzyl.utils.CodeUtil;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.RecordVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author sjqn
 * @date 2023/11/12
 */
@Service
public class CheckInConfigServiceImpl implements CheckInConfigService {


    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private ActFlowCommService actFlowCommService;

    @Autowired
    private AccraditationRecordService accraditationRecordService;

    /**
     * 根据老人id查询入住配置
     *
     * @param elderId
     * @return
     */
    @Override
    public CheckInConfig findCurrentConfigByElderId(Long elderId) {
        return checkInConfigMapper.findCurrentConfigByElderId(elderId);
    }

    /**
     * 入住配置
     *
     * @param checkInConfigDto
     * @return
     */
    @Override
    public ResponseResult checkIn(CheckInConfigDto checkInConfigDto) {

        //判断费用期限是否在入住期限内
        if (
                checkInConfigDto.getCheckInStartTime().isAfter(checkInConfigDto.getCostStartTime())
                        && checkInConfigDto.getCheckInEndTime().isBefore(checkInConfigDto.getCostEndTime())
        ) {
            throw new BaseException("费用期限不在入住期限内");
        }

        //新增入住配置，数据拷贝
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInConfigDto, CheckInConfig.class);
        //查询床位
        Bed bed = bedMapper.getBedById(checkInConfigDto.getBedId());

        //楼层id:房间id:床位id:楼层名称:入住编码  存入到remark中
        String remark = checkInConfigDto.getFloorId()+":"+checkInConfigDto.getRoomId()+":"+checkInConfigDto.getBedId()
                +":"+checkInConfigDto.getFloorName()+":"+checkInConfigDto.getCode();
        checkInConfig.setRemark(remark);

        //床位编号
        checkInConfig.setBedNo(bed.getBedNumber());

        checkInConfigMapper.insert(checkInConfig);

        //更新床位状态
        bed.setBedStatus(2);
        bedMapper.updateBed(bed);

        //保存老人与床位的关系
        Elder elder = elderMapper.selectByPrimaryKey(checkInConfigDto.getElderId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elderMapper.updateByPrimaryKeySelective(elder);

        //更新入住状态
        CheckIn checkIn = checkInMapper.selectByPrimaryKey(checkInConfigDto.getCheckInId());
        checkIn.setFlowStatus(CheckIn.FlowStatus.SIGN.getCode());
        //生成一个合同编号
        String htCode = CodeUtil.generateCode("HT", redisTemplate, 5);
        checkIn.setRemark(htCode);
        //入住时间
        checkIn.setCheckInTime(checkInConfigDto.getCheckInStartTime());
        checkInMapper.updateByPrimaryKeySelective(checkIn);

        //获取当前登录用户
        String subject = UserThreadLocal.getSubject();
        User user = JSON.parseObject(subject, User.class);


        //完成任务
        actFlowCommService.completeProcess("",checkInConfigDto.getTaskId(),user.getId().toString(),1,null);

        //保存操作记录
        Long nextAssignee = actFlowCommService.getNextAssignee("checkIn-new", "checkIn-new:" + checkIn.getId());

        RecordVo recoreVo = getRecordVo(checkIn,
                user, AccraditationRecordConstant.AUDIT_STATUS_PASS,
                "同意", "养老顾问处理-入住配置",
                "法务处理-签约办理", nextAssignee
                ,AccraditationRecordConstant.RECORD_HANDLE_TYPE_PROCESSED);
        accraditationRecordService.insert(recoreVo);

        return ResponseResult.success();
    }

    /**
     * 封装审核记录参数
     *
     * @param checkIn      入住对象
     * @param user         当前登录用户
     * @param status       审核状态
     * @param option       操作意见
     * @param step         当前步骤
     * @param nextSetp     下一步操作人
     * @param nextAssignee 下一个审核人
     * @param handleType   处理类型（0:已审批，1：已处理）
     * @return
     */
    private RecordVo getRecordVo(CheckIn checkIn, User user, Integer status, String option, String step, String nextSetp, Long nextAssignee, Integer handleType) {

        RecordVo recordVo = new RecordVo();
        recordVo.setId(checkIn.getId());
        recordVo.setType(AccraditationRecordConstant.RECORD_TYPE_CHECK_IN);
        recordVo.setFlowStatus(checkIn.getFlowStatus());
        recordVo.setHandleType(handleType);
        recordVo.setStatus(status);
        recordVo.setOption(option);
        recordVo.setNextStep(nextSetp);
        recordVo.setNextAssignee(nextAssignee);
        recordVo.setUserId(user.getId());
        recordVo.setStep(step);
        recordVo.setRealName(user.getRealName());

        return recordVo;
    }
}
